package com.webwork.mood.record.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.webwork.mood.common.controller.SuperCtrl;
import com.webwork.mood.record.dataobject.AwardInfo;
import com.webwork.mood.record.dataobject.DrawInfo;
import com.webwork.mood.record.dataobject.DrawRecord;
import com.webwork.mood.record.dataobject.MoodRecord;
import com.webwork.mood.record.service.AwardService;
import com.webwork.mood.record.service.DrawAwardService;
import com.webwork.mood.record.service.DrawRecordService;
import com.webwork.mood.record.service.MoodService;
import com.webwork.mood.system.dataobject.User;
import com.webwork.mood.system.service.UserService;
import com.webwork.mood.util.DateFormat;
import com.webwork.mood.util.Paging;
import com.webwork.mood.util.StrManager;

@Controller
@RequestMapping(value = "/record")
public class DrawRecordController extends SuperCtrl {

	@Autowired
	private UserService userSve;
	
	@Autowired
	private DrawRecordService recordSve;
	
	@Autowired
	private AwardService awardSve;
	
	@Autowired
	private DrawAwardService drawAwardSve;
	
	@Autowired
	private MoodService moodSve;
	
	@RequestMapping(value = "/drawRecord")
	@Override
	public String mainPage() {
		return "drawRecord";
	}
	
	@RequestMapping(value = "queryDrawRecordList")
	@ResponseBody
	public ResponseEntity<String> queryList(
			@RequestParam(value = "page") int page,
			@RequestParam(value = "rows") int rows,
			@RequestParam(required = false, value = "userName") String userName)
					throws Exception {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		Map<String, Object> ret = new HashMap<String, Object>();

		User queryObj = new User();
		if (!StrManager.isEmpty(userName)) {
			queryObj.setUserName(userName);
		}
		List<User> users = userSve.query(queryObj);
		if (users != null && users.size() > 0) {
			DrawRecord recordQuery = new DrawRecord();
			recordQuery.setUserId(users.get(0).getUserId());
			ret.put("total", recordSve.count(recordQuery));
			List<DrawRecord> list = recordSve.query(recordQuery, new Paging(page, rows));
			for (DrawRecord record : list) {
				AwardInfo award = awardSve.get(record.getAwardName());
				if (award != null) {
					record.setAwardFullName(award.getFullName());
				}
			}
			ret.put("rows", list);
		} else {
			ret.put("total", 0);
			ret.put("rows", new ArrayList<DrawRecord>());
		}
		return new ResponseEntity<String>(new Gson().toJson(ret).toString(), responseHeaders, HttpStatus.CREATED);
	}
	
	@RequestMapping(value = "queryDrawInfoList")
	@ResponseBody
	public ResponseEntity<String> queryDrawList(
			@RequestParam(required = false, value = "userName") String userName)
					throws Exception {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		List<DrawInfo> rets = new ArrayList<DrawInfo>();

		User queryObj = new User();
		if (!StrManager.isEmpty(userName)) {
			queryObj.setUserName(userName);
		}
		List<User> users = userSve.query(queryObj);
		if (users != null && users.size() > 0) {
			DrawInfo drawQuery = new DrawInfo();
			drawQuery.setUserId(users.get(0).getUserId());
			rets = recordSve.query(drawQuery);
			for (DrawInfo draw : rets) {
				AwardInfo award = awardSve.get(draw.getAwardName());
				if (award != null) {
					draw.setAwardFullName(award.getFullName());
					draw.setNeedCount(award.getCount());
				}
			}
		}
		return new ResponseEntity<String>(new Gson().toJson(rets).toString(), responseHeaders, HttpStatus.CREATED);
	}
	
	@RequestMapping(value = "recAward")
	@ResponseBody
	public String recAward(
			@RequestParam(value = "userId") String userId,
			@RequestParam(value = "awardName") String awardName,
			@RequestParam(value = "amount") int amount)
					throws Exception {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		DrawInfo info = recordSve.get(userId, awardName);
		AwardInfo award = awardSve.get(info.getAwardName());
		if (amount == 0) {
			return FAIL;
		}
		int canRec = 0;
		if (info.getPatchCount() < award.getCount()) {
			return "noEnough";
		} else if (info.getPatchCount() == award.getCount()) {
			canRec = 1;
		} else {
			canRec = info.getPatchCount() / award.getCount();
		}
		if (amount > canRec) {
			return "noEnough";
		}

		info.setPatchCount(info.getPatchCount() - (amount * award.getCount()));
		recordSve.update(info);
		
		//插入领奖记录
		DrawRecord record = new DrawRecord();
		record.setUserId(userId);
		record.setAwardName(awardName);
		record.setRecCount(amount);
		record.setDrawDate(new Date());
		recordSve.insert(record);
		return SUCCESS;
	}
	
	@RequestMapping(value = "/doDraw", produces = "text/html;charset=UTF-8") //避免json中文?乱码
	@ResponseBody
	public String doDraw(
			@RequestParam(value = "telephone") String telephone,
			@RequestParam(value = "weixinId") String weixinId,
			HttpServletResponse response) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		User queryObj = new User();
		if (!StrManager.isEmpty(telephone)) {
			queryObj.setTelephone(telephone);
		} else {
			queryObj.setWeixinId(weixinId);
		}
		List<User> users = userSve.query(queryObj);
		if (users != null && users.size() > 0) {
			User user = users.get(0);
			user.setWeixinId(weixinId);
			userSve.update(user);
			
			String nowDate = DateFormat.SHORT_NUMBER.format(new Date());
			
			MoodRecord recordQuery = new MoodRecord();
			recordQuery.setRecordId("MR" + nowDate);
			recordQuery.setWeixinId(weixinId);
			List<MoodRecord> mrs = moodSve.query(recordQuery);
			if (mrs != null && mrs.size() > 0) {
				MoodRecord mr = mrs.get(0);
				mr.setUserId(user.getUserId());
				moodSve.update(mr);
			}
			
			List<DrawRecord> records = recordSve.getUserDraw(user.getUserId(), new Date());
			if (records != null && records.size() > 0) {
				for (DrawRecord record : records) {
					if (record.getDrawCount() > 0) {
						return "您今天已进行过抽奖!";
					}
				}
			}
			return SUCCESS;
		} else {
			return "该手机号未在本系统登记,请联系管理员进行信息更新!";
		}
	}
	
	@RequestMapping(value = "/showDraw", produces = "text/html;charset=UTF-8") //避免json中文?乱码
	@ResponseBody
	public String showDraw(
			@RequestParam(value = "weixinId") String weixinId,
			HttpServletResponse response) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		User queryObj = new User();
		queryObj.setWeixinId(weixinId);
		List<User> users = userSve.query(queryObj);
		if (users != null && users.size() > 0) {
			User user = users.get(0);
			
			AwardInfo info = drawAwardSve.generateAward();
			System.out.println(new Gson().toJson(info).toString());
			
			//抽奖结果插入记录
			DrawInfo drawinfo = recordSve.get(user.getUserId(), info.getAwardName());
			if (drawinfo != null) {
				drawinfo.setPatchCount(drawinfo.getPatchCount() + info.getCount());
				recordSve.update(drawinfo);
			} else {
				drawinfo = new DrawInfo();
				drawinfo.setUserId(user.getUserId());
				drawinfo.setAwardName(info.getAwardName());
				drawinfo.setPatchCount(info.getCount());
				recordSve.insert(drawinfo);
			}
			
			DrawRecord record = new DrawRecord();
			record.setUserId(user.getUserId());
			record.setDrawDate(new Date());
			record.setAwardName(info.getAwardName());
			record.setDrawCount(info.getCount());
			recordSve.insert(record);
			AwardInfo award = awardSve.get(info.getAwardName());
			if (award != null) {
				return "恭喜您获得" + award.getFullName() + "碎片 X " + info.getCount();
			} else {
				return FAIL;
			}
		} else {
			return FAIL;
		}
	}
	
	@RequestMapping(value = "/getAwardRecord", produces = "text/html;charset=UTF-8") //避免json中文?乱码
	@ResponseBody
	public String getAwardRecord(
			@RequestParam(value = "telephone") String telephone,
			@RequestParam(value = "weixinId") String weixinId,
			HttpServletResponse response) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		List<User> users = new ArrayList<User>();
		User queryObj = new User();
		if (!StrManager.isEmpty(telephone)) {
			queryObj.setTelephone(telephone);
			users = userSve.query(queryObj);
		} else {
			queryObj.setWeixinId(weixinId);
			users = userSve.query(queryObj);
			if (users == null || users.size() < 1) {
				return "needTel";
			}
		}
		if (users != null && users.size() > 0) {
			User user = users.get(0);
			user.setWeixinId(weixinId);
			userSve.update(user);
			
			String nowDate = DateFormat.SHORT_NUMBER.format(new Date());
			MoodRecord recordQuery = new MoodRecord();
			recordQuery.setRecordId("MR" + nowDate);
			recordQuery.setWeixinId(weixinId);
			List<MoodRecord> mrs = moodSve.query(recordQuery);
			if (mrs != null && mrs.size() > 0) {
				MoodRecord mr = mrs.get(0);
				mr.setUserId(user.getUserId());
				moodSve.update(mr);
			}
			
			List<DrawInfo> rets = new ArrayList<DrawInfo>();
			
			DrawInfo drawQuery = new DrawInfo();
			drawQuery.setUserId(users.get(0).getUserId());
			rets = recordSve.query(drawQuery);
			for (DrawInfo draw : rets) {
				AwardInfo award = awardSve.get(draw.getAwardName());
				if (award != null) {
					draw.setAwardFullName(award.getFullName());
					draw.setNeedCount(award.getCount());
				}
			}
			return new Gson().toJson(rets).toString();
		} else {
			return "noexist";
		}
	}
	
	@RequestMapping(value = "/getDrawRecord", produces = "text/html;charset=UTF-8") //避免json中文?乱码
	@ResponseBody
	public String getDrawRecord(
			@RequestParam(value = "telephone") String telephone,
			@RequestParam(value = "weixinId") String weixinId,
			HttpServletResponse response) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		List<User> users = new ArrayList<User>();
		User queryObj = new User();
		if (!StrManager.isEmpty(telephone)) {
			queryObj.setTelephone(telephone);
			users = userSve.query(queryObj);
		} else {
			queryObj.setWeixinId(weixinId);
			users = userSve.query(queryObj);
			if (users == null || users.size() < 1) {
				return "needTel";
			}
		}
		if (users != null && users.size() > 0) {
			User user = users.get(0);
			user.setWeixinId(weixinId);
			userSve.update(user);
			
			List<String> ret = new ArrayList<String>();
			
			DrawRecord drawQuery = new DrawRecord();
			drawQuery.setUserId(users.get(0).getUserId());
			List<DrawRecord> records = recordSve.query(drawQuery);
			for (DrawRecord record : records) {
				String str = "";
				AwardInfo award = awardSve.get(record.getAwardName());
				if (award != null) {
					record.setAwardFullName(award.getFullName());
				}
				String date = DateFormat.Simple.format(record.getDrawDate());
				str += date;
				if (record.getDrawCount() > 0) {
					str += " 获得 " + record.getAwardFullName() + " 碎片 " + record.getDrawCount() + " 块";
				} else if (record.getRecCount() > 0) {
					str += " 换取 " + record.getAwardFullName() + " " + record.getRecCount() + " 张";
				}
				ret.add(str);
			}
			return new Gson().toJson(ret).toString();
		} else {
			return "noexist";
		}
	}
	
}
